<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class MessageAction extends BaseAccountAction {

	//显示Message
	public function index() {
		$this->init();
		$where = '(user_id=' . $this->uid . ' and status<2) or (from_id=' . $this->uid . ' and from_status<2)';
		$Message = D('Message');
		import("@.ORG.Util.Page");
		$Count = $Message->where($where)->count();
		$Page = new Page($Count, 10);
		$show = $Page->show();
		$data = $Message->where($where)->order('last_time desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
		$this->assign('data', $data);
		$this->assign('page', $show);
		$this->display();
	}

	//显示单条Message
	public function show() {
		$this->auth();
		$id = (int) $_GET['id'];
		//更新阅读状态
		$Message = D("Message");
		$message = $Message->relation(array("tweets", "reply"))->find($id);
		if ($message) {
			$Message->where("message_id=" . $id)->setField($this->uid == (int) $message['user_id'] ? "status" : "from_status", 1);
			S("message_new_" . $this->uid, null);
			$this->init();
			if ($message['tweets']) {
				$view = new View();
				$view->assign("tweets", $message['tweets']);
				$message['tweets']['title'] = $view->fetch(HTML_PATH . "/_tweets/_" . (int) $message['tweets']['cate_id'] . ".html");
			}
			$this->assign("school", get_shcool_info($message['tweets']['school_id']));
			$this->assign("message", $message);
			$this->display("Message_show");
		} else {
			//跳转
			$this->error("数据不存在！");
		}
	}

	//删除Message
	public function delete() {
		$id = (int) $_GET['id'];
		$message = D("Message")->find($id);
		if ($message) {
			if ($this->uid == (int) $message['user_id']) {
				D("Message")->where("message_id =" . $id)->setField("status", 2);
			} else {
				D("Message")->where("message_id =" . $id)->setField("from_status", 2);
			}
			S("message_new_" . $this->uid == (int) $message['user_id'] ? $this->uid : (int) $message['user_id'], null);
			$this->success('删除成功!', __URL__);
		} else {
			$this->error('请选择需要删除的消息!');
		}
	}

	//回复
	public function reply() {
		$content = trim($_POST['content']);
		$message_id = $_POST['message_id'];
		empty($content) && $this->error("请填写回复内容");
		$Message = D("Message");
		$message = $Message->find($message_id);
		if ($this->uid == (int) $message['user_id']) {
			$Message->where("message_id=" . $message_id)->data(array(
				"from_status" => 0,
				"last_time" => time(),
			))->save();
		} else {
			$Message->where("message_id=" . $message_id)->data(array(
				"status" => 0,
				"last_time" => time(),
			))->save();
		}
		!$message && $this->error("参数错误");
		D("Reply")->data(array(
			"message_id" => $message_id,
			"user_id" => $this->uid,
			"content" => $message['content'],
			"create_time" => time(),
		))->add();
		$this->success("回复成功");
	}

//	private function showNickName($uid) {
//		return $this->uid == $message['user_id'] ? $message['user_nickname'] : $message['from_nickname'];
//	}
}

?>
